package com.mm.fam.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.fam.common.utils.Digests;
import com.mm.fam.common.utils.LoggerUtils;
import com.mm.fam.web.base.CommonConstant;
import com.mm.fam.web.base.ResponseModel;
import com.mm.fam.web.base.ResponseUtil;
import com.mm.fam.web.entity.SysUser;
import com.mm.fam.web.entity.SysUserOrganization;
import com.mm.fam.web.entity.SysUserRole;
import com.mm.fam.web.mapper.SysUserMapper;
import com.mm.fam.web.mapper.SysUserOrganizationMapper;
import com.mm.fam.web.mapper.SysUserRoleMapper;
import com.mm.fam.web.service.SysUserService;
import com.mm.fam.web.vo.OrganizationUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zt
 * @since 2018-09-29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserOrganizationMapper sysUserOrganizationMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public IPage<SysUser> queryUserList(Integer pageNum, Integer pageSize, String search, Integer roleId) {
        String filterWhereStr = null;
        if (StringUtils.isNoneEmpty(search)){
            filterWhereStr = "and (username like '%"+search+"%' or nickname like '%"+search+"%' or email like '%"+search+"%' or telephone like '%"+search+"%')";
        }
        IPage<SysUser> page = new Page<>(pageNum,pageSize);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("roleId", roleId);
        paramMap.put("delFlag", 1);
        paramMap.put("filterWhereStr", filterWhereStr);
        return sysUserMapper.queryUserList(page,paramMap);
    }

    @Override
    public ResponseEntity<ResponseModel<SysUser>> querySysUserInfo(Integer userId) {
        ResponseEntity<ResponseModel<SysUser>> re = null;

        //查询用户信息
        SysUser sysUser = sysUserMapper.selectById(userId);

        //查询用户角色信息
        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUser.setUserRoles(userRoles);

        re = ResponseUtil.success(sysUser);

        return re;
    }

    @Override
    public String saveUser(SysUser user,Integer roleId) throws  RuntimeException {
        Date date=new Date();
        if(user.getId()!=null){
            //修改用户基本信息
            user.setModifyTime(date);
            updateById(user);
            //修改用户角色
            SysUserRole sur = new SysUserRole();
            sur.setRoleId(roleId);
            sysUserRoleMapper.update(sur, new QueryWrapper<SysUserRole>().eq("user_id", user.getId()));
        }else{
            //判断用户名是否存在重复的

            //新增用户基本信息
            user.setCreateTime(date);
            user.setModifyTime(date);
            String password= Digests.shaHex(user.getPassword(), user.getUsername());
            user.setPassword(password);
            try {
                sysUserMapper.insert(user);
            }catch (Exception e){
                e.printStackTrace();
                throw  new RuntimeException("添加用户失败");
            }
            //修改用户角色信息
            SysUserRole sur = new SysUserRole();
            sur.setRoleId(roleId);
            sur.setUserId(user.getId());
            sysUserRoleMapper.insert(sur);
        }
        return "操作成功";
    }

    @Override
    @Transactional(isolation= Isolation.REPEATABLE_READ,propagation= Propagation.REQUIRED)
    public ResponseEntity<ResponseModel<Object>> saveOrUpdateOrganizationUser(OrganizationUser ou) {
        ResponseEntity<ResponseModel<Object>> re = null;
        Date now = new Date();
        if(ou.getId() == null){
            //查询企业用户最大工号
            Integer newMaxNum = sysUserMapper.queryOrganizationUserMaxJobNo() + 1;

            String password= Digests.shaHex("123456", newMaxNum.toString());
            //创建用户
            SysUser su = new SysUser();
            su.setUsername(newMaxNum.toString());
            su.setNickname(ou.getNickname());
            su.setJobNo(newMaxNum);
            su.setEmail(ou.getEmail());
            su.setTelephone(ou.getTelephone());
            su.setPassword(password);
            su.setCreateTime(now);
            su.setCreateId(ou.getCreateId());
            su.setIdentityCard(ou.getIdentityCard());
            su.setSex(ou.getSex());
            su.setBirthday(ou.getBirthday());

            sysUserMapper.insert(su);

            //给用户分配权限
            SysUserRole sur = new SysUserRole();
            sur.setUserId(su.getId());
            sur.setRoleId(3);
            sysUserRoleMapper.insert(sur);

            //给用户初始化组织信息
            List<Integer> organizations = ou.getOrganizations();
            for(Integer oId: organizations){
                SysUserOrganization suo = new SysUserOrganization();
                suo.setUserId(su.getId());
                suo.setOrganizationId(oId);
                sysUserOrganizationMapper.insert(suo);
            }
            re = ResponseUtil.success(null);
        }else{
            //修改用户信息
            SysUser su = new SysUser();
            su.setId(ou.getId());
            su.setNickname(ou.getNickname());
            su.setEmail(ou.getEmail());
            su.setTelephone(ou.getTelephone());
            su.setModifyTime(now);
            su.setIdentityCard(ou.getIdentityCard());
            su.setSex(ou.getSex());
            su.setBirthday(ou.getBirthday());
            sysUserMapper.updateById(su);

            //删除用户部门信息
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("user_id", ou.getId());
            sysUserOrganizationMapper.deleteByMap(paramMap);

            //插入新的部门数据
            List<Integer> organizations = ou.getOrganizations();
            for(Integer oId: organizations){
                SysUserOrganization suo = new SysUserOrganization();
                suo.setUserId(su.getId());
                suo.setOrganizationId(oId);
                sysUserOrganizationMapper.insert(suo);
            }
            re = ResponseUtil.success(null);
        }
        return re;
    }

    @Override
    public ResponseEntity<ResponseModel<OrganizationUser>> queryOrganizationUserInfo(Integer id) {
        ResponseEntity<ResponseModel<OrganizationUser>> re = null;
        OrganizationUser ou = new OrganizationUser();
        List<Integer> organizations = new ArrayList<>();

        SysUser sysUser = sysUserMapper.selectById(id);
        List<SysUserOrganization> uoList = sysUserOrganizationMapper.selectList(new QueryWrapper<SysUserOrganization>().eq("user_id", id));

        for(SysUserOrganization suo : uoList){
            organizations.add(suo.getOrganizationId());
        }

        ou.setId(id);
        ou.setOrganizations(organizations);
        ou.setNickname(sysUser.getNickname());
        ou.setIdentityCard(sysUser.getIdentityCard());
        ou.setTelephone(sysUser.getTelephone());
        ou.setEmail(sysUser.getTelephone());
        ou.setBirthday(sysUser.getBirthday());
        ou.setSex(sysUser.getSex());
        ou.setStatus(sysUser.getStatus());

        re = ResponseUtil.success(ou);

        return re;
    }

    @Override
    public String updateLoginTime(Integer id) throws  RuntimeException{
        SysUser user =new SysUser();
        user.setId(id);
        user.setLastLoginTime(new Date());
        boolean flag = updateById(user);
        if (flag) {
            return CommonConstant.Message.OPTION_FAILURE;
        }
        return CommonConstant.Message.OPTION_SUCCESS;
    }

    @Override
    public String delete(List<Integer> ids) throws  RuntimeException{
        try {
            sysUserMapper.deleteBatchIds(ids);
        } catch (Exception e) {
            LoggerUtils.error(getClass(), "删除管理员失败:" + e.getMessage());
            throw new RuntimeException("删除失败");
        }
        return "删除成功";
    }

    @Override
    public String saveSysUser(SysUser sysUser) {
        int result;
        int updataResult;
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("username",sysUser.getUsername());
        // 判断是否激活
        if (null == sysUser.getStatus() || !CommonConstant.UsedStatus.USABLE.equals(sysUser.getStatus())) {
            sysUser.setStatus(0);
        }
        if (sysUser.getId() != null) {
            //如果编辑部修改内容直接保存,否则先判断用户名是否重复并且返回前端相应提醒
            map.put("id",sysUser.getId());
            result = sysUserMapper.queryUserNameExist(map);
            if(result>0){
                Date date = new Date();
                sysUser.setModifyTime(date);
                updataResult = sysUserMapper.updataSysUser(sysUser);
                if (updataResult>0){
                    return "操作成功";
                }else {
                    return "操作失败";
                }
            }else {
                //判断用户名是否重复,sql需要用户名,返回的数值做比较
                map.put("id",null);
                result = sysUserMapper.queryUserNameExist(map);
                if (result ==0 ){
                    Date date = new Date();
                    sysUser.setModifyTime(date);
                    updataResult = sysUserMapper.updataSysUser(sysUser);
                    if (updataResult>0){
                        return "操作成功";
                    }else {
                        return "操作失败";
                    }
                }else {
                    return "用户名称重复,请重新输入";
                }
            }
        }else {
            // 新建时判断是否存在用户名
            result = sysUserMapper.queryUserNameExist(map);
            if(result>0){
                return "用户名称重复,请重新输入";
            }else {
                // 新建时,前端传入的明文密码进行散列加密
                sysUser.setPassword(Digests.shaHex(sysUser.getPassword(), sysUser.getUsername()));
                save(sysUser);
                return "操作成功";
            }
        }
    }

    /**
     * 根据id逻辑删除用户
     *
     * @param userId
     * @return java.lang.Integer
     * @author MaLiZhi
     * @date 2019/03/11 13:09
     */
    @Override
    public Integer delUserbyId(Integer userId) {
        return sysUserMapper.delUserbyId(userId);
    }



    @Override
    public boolean checkUsername(String username) {
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Integer count = sysUserMapper.selectCount(qw);
        return count>0?false:true;
    }

    @Override
    public List<SysUser> queryRiskerListSimple() {
        return sysUserMapper.queryRiskerListSimple();
    }
}
